//
//  UTMineViewController.swift
//  UniversalTool
//
//  Created by LGB on 2025/3/3.
//

import UIKit
import ProgressHUD

class UTMineViewController: UTBaseViewController {

    @IBOutlet weak var navigationHeight: NSLayoutConstraint!
    @IBOutlet weak var menmberTitleLabel: UILabel!
    @IBOutlet weak var menmberTipsLabel: UILabel!
    @IBOutlet weak var openMembershipButton: UIButton!
    @IBOutlet weak var giveMemberView: UIView!
    @IBOutlet weak var giveMemberHeight: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
    }
    
    fileprivate func  setupViews() {
        view.backgroundColor = UIColor(hexString: "#F7F7F9")
        navigationHeight.constant = UIApplication.shared.statusBarFrame.size.height + 44
        NotificationCenter.default.addObserver(self, selector: #selector(subscriptionReloadData(_:)), name: NSNotification.Name(rawValue: "ZSSubscriptionReloadData"), object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let bundleID = Bundle.main.bundleIdentifier {
            fetchSubscriptionPrice(buildId: bundleID)
        }
    }
    
    @IBAction func goBack(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc func subscriptionReloadData(_ sender: NotificationCenter) {
        if let bundleID = Bundle.main.bundleIdentifier {
            fetchSubscriptionPrice(buildId: bundleID)
        }
    }
    
    
    @IBAction func didOpenMenber(_ sender: UIButton) {
        let vc = UTSubscriptionViewController()
        vc.modalPresentationStyle = .overFullScreen
        self.present(vc, animated: false)
    }
    
    @IBAction func goReceiveGuide(_ sender: UITapGestureRecognizer) {
        let vc = UTReceiveGuideViewController()
        vc.modalPresentationStyle = .overFullScreen
        self.present(vc, animated: false)
        vc.receiveHandler = { [self] status in
            giveMemberView.isHidden = true
            giveMemberHeight.constant = 0
            if let bundleID = Bundle.main.bundleIdentifier {
                fetchSubscriptionPrice(buildId: bundleID)
            }
        }
    }
    
    @IBAction func goUserAgreement(_ sender: UITapGestureRecognizer) {
        let vc = UTWebViewController()
        vc.linkUrl = userProtocolLink
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func goPrivacyAgreement(_ sender: UITapGestureRecognizer) {
        let vc = UTWebViewController()
        vc.linkUrl = privacyAgreementLink
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func goFeedback(_ sender: UITapGestureRecognizer) {
        let vc = UTFeedbackViewController()
        vc.modalPresentationStyle = .overFullScreen
        self.present(vc, animated: false)
    }
    
    func fetchSubscriptionPrice(buildId: String) {
        ProgressHUD.show()
        let urlString = baseUrl + "/lbbserves/api/appdingyue/info"
        guard let url = URL(string: urlString) else {
            print("Invalid URL")
            return
        }

        let parameters: [String: Any] = ["packageName": buildId]
        let jsonData = try? JSONSerialization.data(withJSONObject: parameters)

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            ProgressHUD.dismiss()
            if let error = error {
                print("Error: \(error)")
                return
            }

            guard let data = data else {
                print("No data received")
                return
            }

            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], let data = json["data"] as? Dictionary<String, Any>, let remark = data["remark"] as? String {
                    DispatchQueue.main.async {
                        if let orderid = UserDefaults.standard.object(forKey: "orderId") as? String, !orderid.isEmpty  {
                            self.openMembershipButton.isHidden = true
                            self.menmberTitleLabel.text = "你已是超级会员"
                            self.giveMemberView.isHidden = true
                            self.giveMemberHeight.constant = 0
                            if let expiresDate = UserDefaults.standard.object(forKey: expiresDateIdentifier) as? Date {
                                let dateFormatter = DateFormatter()
                                dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
                                dateFormatter.locale = Locale(identifier: "en_US_POSIX")
                                dateFormatter.timeZone = TimeZone.current
                                let dateString = dateFormatter.string(from: expiresDate)
                                self.menmberTipsLabel.isHidden = false
                                self.menmberTipsLabel.text = dateString + "到期"
                            }else if let expiresDate = UserDefaults.standard.object(forKey: expiresDateIdentifier) as? String {
                                self.menmberTipsLabel.isHidden = false
                                self.menmberTipsLabel.text = expiresDate
                            }
                        }else {
                            guard let zsBenefitDate = UserDefaults.standard.object(forKey: utBenefit) as? Date else {
                                if remark.contains("【活动中】") {
                                    self.giveMemberView.isHidden = false
                                    self.giveMemberHeight.constant = 52
                                }else {
                                    self.giveMemberView.isHidden = true
                                    self.giveMemberHeight.constant = 0
                                }
                                return
                            }
                            let dateFormatter = DateFormatter()
                            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
                            dateFormatter.locale = Locale(identifier: "en_US_POSIX")
                            dateFormatter.timeZone = TimeZone.current
                            let calendar = Calendar.current
                            let dateString = dateFormatter.string(from: calendar.date(byAdding: .day, value: 3, to: zsBenefitDate)!)
                            self.menmberTipsLabel.isHidden = false
                            self.menmberTipsLabel.text = dateString + "到期"
                        }
                    }
                }
                
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }

        task.resume()
    }
}
